package com.codeying.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 拦截用户直接访问jsp页面
 */
@WebFilter(urlPatterns = {"/pages/*","/hello.jsp"})
public class PageFilter implements Filter {

    @Override
    public void destroy() {
        System.out.println("PageFilter destroy....");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if(req.getSession().getAttribute("user")!=null){
            //放行！
            chain.doFilter(request,response);
        }else {
            req.getRequestDispatcher("/login.jsp").forward(req, response);
        }
    }
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("PageFilter init....");
    }
}
